﻿using System;
using System.Collections.Generic;
using System.Linq;
using Analyze.Calculator;
using Analyze.Manager;
using Analyze.Provider;
using Common.Dao;
using Common.Model;
using Common.Util;

namespace Analyze.Script
{
    public class ModelGenerateScript
    {
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(ModelGenerateScript));
        
         public static void Run()
        {
            Log.Info("ModelGenerateScript start");
            
            List<DxwEvent> eventsWithWords = DxwEventDao.GetEventsWithWords();

            //需要丢弃的板块不参与模型生成
            List<string> newBlocksDroped = NewBlockDao.GetNewBlocksDroped().Select(m=>m.BlockName).ToList();

            foreach (var newBlock in newBlocksDroped)
            {
                eventsWithWords = eventsWithWords.Where(m => !m.Block.Equals(newBlock)).ToList();
            }
            
            //模型生成
            List<ClassifyModel> models = new List<ClassifyModel>();
            foreach (var eventsWithWord in eventsWithWords)
            {
                var words = Util.SplitWords(eventsWithWord.Words).Where(m=>m.Length>1).ToList();

                var classifyModels = words.Where(m => !StopWordManager.GetInstance().IsStopWord(m)).Select(m => new ClassifyModel
                {
                    UpdateTime = DateTime.Now,
                    Block = eventsWithWord.Block,
                    Word = m,
                    WordConditionaProbability =
                        Probability.CalculateClassConditionalProbability(m, eventsWithWord.Block),
                    WordPriorProbability = Probability.CalculatePriorProbability(eventsWithWord.Block)
                }).ToList();
                classifyModels.ForEach(m =>
                {
                    Log.Info("========================");
                    Log.Info("Block = "+ m.Block);
                    Log.Info("Word = "+ m.Word);
                    Log.Info("WordConditionaProbability = "+ m.WordConditionaProbability);
                    Log.Info("WordPriorProbability = "+ m.WordPriorProbability);
                });

                models.AddRange(classifyModels);
            }

            ClassifyModelDao.ClearClassify();
            ClassifyModelDao.BatchSaveMode(models);
            TrainingDataProvider.GetInstance().Reload();
            Log.Info("ModelGenerateScript end");
        }
    }
}